#include "tcpInit.h"

int tcp_init(const char *ip, const char *port)
{
    // 创建socket
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    int flag = 1;
    setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&flag,sizeof(flag));
    // 错误处理
    if (sockfd < 0)
    {
        LOG_ERROR("socket create failed");
        return -1;
    }
    // 设置端口复用
    setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &(int){1}, sizeof(int));
    // 绑定ip和端口
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(atoi(port));
    addr.sin_addr.s_addr = inet_addr(ip);
    bind(sockfd, (struct sockaddr *)&addr, sizeof(addr));
    // 开启监听
    listen(sockfd, 5);

    return sockfd;
}